package com.xzx.zookeeper.lock;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @version 1.0
 * @auther xinzhixuan
 * @date 2022/9/3 13:31
 */
public class ZkClient {
    private static volatile ZkClient instance;
    private ZooKeeper zooKeeper;
    private ZkClient() {
        try {
            initConnection();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

        // 如果存在发生异常忽略即可
        try {
            zooKeeper.create("/locks", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (Exception e) {
            System.out.println("根节点可能存在了");
        }
    }

    public static ZkClient getInstance() {
        if (instance == null) {
            synchronized (ZkClient.class) {
                if (instance == null) {
                    instance = new ZkClient();
                }
            }
        }

        return instance;
    }

    private void initConnection() throws IOException, InterruptedException {

        CountDownLatch latch = new CountDownLatch(1);
        this.zooKeeper = new ZooKeeper("localhost:2181", 2000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    System.out.println("连接成功=============");
                    latch.countDown();
                }
            }
        });
        latch.await();
    }

    public ZooKeeper getZooKeeper() {
        return zooKeeper;
    }
}
